package com.example.studyproject.advice;

import com.example.studyproject.annotation.EncryptionAnnotation;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @program: StudyProject
 * @description: 统一格式返回切面
 * @author: kangwei
 * @create: 2023-03-14 14:41
 **/
@ControllerAdvice  // 执行过程 controllerAdvice注解--派生component组件，所有的组件初始化都会执行 InitializingBean 接口，
//  RequestMappingHandlerAdapter 类中的 afterPropertiesSet() 方法 调用initControllerAdviceCache()方法 ，此方法会扫描 ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice<Response> {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Response beforeBodyWrite(Response body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 加密
        EncryptionAnnotation annotation = returnType.getMethodAnnotation(EncryptionAnnotation.class);
        if (null != annotation && annotation.encryp()) {
            Object data = body.getData();
            if (null != data) {
                // 加密
            }
            body.setData(data);
        }
        return body;
    }
}
